<template>
    <view class="bg-content">
        <div style="display: flex;">
            <div style="width: 100%">
                <u-button plain type="success" @click="scan">扫一扫</u-button>
            </div>
            <div style="width: 100%">
                <u-button plain type="primary" @click="showPasteQRCodeActionSheet">粘贴二维码</u-button>
            </div>
        </div>

        <u-cell-group title="已关联商城">
            <u-cell-item v-for="(item, index) of globalVariable.userInfo.tbCommunityUserList" :key="index" :arrow="false" use-label-slot
                         @click="switchCommunity(item)">
                <div slot="icon">
                </div>
                <div slot="title" style="padding-left: 10px;">
                    <div>
                        <div>
                            {{item.tbCommunity.name}}
                        </div>
                        <div v-if="item.tbCommunity.provinceName && item.tbCommunity.cityName && item.tbCommunity.areaName">
                            所属区域：{{item.tbCommunity.provinceName}}-{{item.tbCommunity.cityName}}-{{item.tbCommunity.areaName}}
                        </div>
                    </div>
                </div>
                <div slot="label">
                    <u-tag v-if="globalVariable.userInfo.tbCommunityUser.id === item.id"
                           text="当前选中" type="error" mode="plain" size="mini" style="margin-right: 10px;"/>

                    <u-tag v-if="item.isDefault"
                           text="默认选中" type="primary" mode="plain" size="mini" style="margin-right: 10px;"/>

                    <u-tag v-if="globalVariable.orderSequenceNumber"
                           :text="`餐饮号：${globalVariable.orderSequenceNumber}`" type="success" mode="plain" size="mini" style="margin-right: 10px;"/>

                    <u-tag v-if="item.tbCommunity.id === globalVariable.userInfo.tbCommunityUser.tbCommunity.id && globalVariable.userInfo.customerName"
                           :text="`选中客户：${globalVariable.userInfo.customerName}`" type="success" mode="plain" size="mini" style="margin-right: 10px;"/>
                </div>

                <div slot="label" v-if="!item.enabledLogin">
                    该商城禁止访问
                </div>
                <u-icon slot="right-icon" size="40" name="arrow-right" style="padding-left: 20px;"></u-icon>
                <!--默认value属性-->
                <div>
                </div>
            </u-cell-item>
        </u-cell-group>

        <u-popup v-model="isShowActionSheet" mode="bottom">
            <view class="bg-content">
                <u-button plain v-for="(item, index) of actionSheetActions" :key="index" :hair-line="false"
                          @click="onSelect(item, index)" :disabled="item.disabled">{{item.name}}
                </u-button>

                <u-button plain v-if="isShowSwitchCustomer" :hair-line="false" @click="switchCustomer()">切换客户</u-button>
                <u-button plain v-if="tbCommunityUser && tbCommunityUser.tbCommunity.qrCode" :hair-line="false" @click="showQRCode()">生成商城二维码</u-button>

                <u-button plain @click="onCancel" :custom-style="{'margin-top': '10px'}">取消</u-button>
            </view>
        </u-popup>

        <!--显示二维码-->
        <u-popup v-model="isShowQrCode" mode="bottom" :closeable="true">
            <view style="text-align: center;">
                <div style="padding: 5px; margin-bottom: 10px; background: white;" v-if="tbCommunityUser">
                    商城名称：{{tbCommunityUser.tbCommunity.name}}
                </div>
                <div style="display: flex;">
                    <div style="width: 100%;">
                    </div>
                    <div>
                        <canvas id="qrcode" canvas-id="qrcode" style="width: 154px;height: 154px;" @click="previewImage()"/>
                    </div>
                    <div style="width: 100%;">
                    </div>
                </div>
                <div style="padding: 5px; margin-top: 10px; background: white;">
                    提示：点击二维码生成图片，长按图片可保存到本地
                </div>
            </view>
        </u-popup>

        <!--粘贴二维码字符串-->
        <u-modal v-model="isShowPasteQRCodeActionSheet" :confirm-text="'识别二维码内容'" :show-cancel-button="true"
                 @cancel="isShowPasteQRCodeActionSheet = false" @confirm="recognizeQRCode()">
            <view class="slot-content" style="padding: 15px;">
                <u-input type="textarea" height="40" placeholder="请将识别后的二维码内容粘贴至此" v-model="pasteQRCode"/>
            </view>
        </u-modal>

        <div style="margin-top: 10px; margin-bottom: 10px;">
            <official-account style="width: 100%;"></official-account>
        </div>
    </view>
</template>

<script>

    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {TbCommunityUserService} from "@/dev/services/tb-community-user.service";
    import {LocalStorageUtil} from "@/dev/core/utils/local-storage.util";
    import {SysUserService} from "@/dev/services/sys-user.service";
    import uQRCode from '@/pages/sub/sub1-tabs/static/plugins/uqrcode.js'

    export default {
        data() {
            return {
                // 切换商城
                isShowActionSheet: false,
                actionSheetActions: [
                    {code: 1, name: "访问该商城", disabled: false},
                    {code: 2, name: "设为默认访问", disabled: false},
                ],
                isShowSwitchCustomer: false, // 是否显示切换客户选项（公司业务员才有该选项）

                // 粘贴二维码
                isShowPasteQRCodeActionSheet: false,
                pasteQRCode: "",

                //选中的商城
                tbCommunityUser: null,

                isShowQrCode: false  // 是否显示商城二维码
            }
        },
        methods: {
            scan() {
                const _self = this;
                uni.scanCode({
                    success: function (res) {
                        console.log('条码内容：' + res.result);
                        try {
                            if (res.result.indexOf("?") === -1) {
                                _self.handleQrCode(res.result);
                            } else {
                                // 如果扫码结果是url，则取url中的参数
                                let urlParams = CommonUtil.getUrlParams(res.result);
                                _self.handleQrCode(urlParams.qrCode);
                            }
                        } catch (e) {
                            _self.handleQrCode(null);
                        }
                    }
                });
            },
            /**
             * 处理二维码
             */
            handleQrCode(qrcode) {
                const _self = this;
                if (!qrcode) {
                    CommonUtil.toast("二维码无效");
                } else {
                    // 校验二维码是否有效
                    new TbCommunityUserService().verifyQRCode(qrcode).then(scanResult => {
                        if (scanResult.status === "success") {
                            // 先判断商城是否已关联
                            let tbCommunityUser = null;
                            _self.globalVariable.userInfo.tbCommunityUserList.forEach(item => {
                                if (item.tbCommunity.id === scanResult.tbCommunityUser.communityId) {
                                    tbCommunityUser = item;
                                }
                            });
                            // 已经关联该商城，则直接切换到该商城。
                            if (tbCommunityUser) {
                                _self.tbCommunityUser = tbCommunityUser;
                                // 保存扫码关联的餐饮号
                                _self.globalVariable.orderSequenceNumber = scanResult.tbCommunityUser.orderSequenceNumber;
                                // 切换到该商城
                                _self.onSelect({detail: {code: 1}});
                                return;
                            }

                            CommonUtil.alert({
                                title: '是否访问该商城？',
                                content: scanResult.communityName,
                                showCancel: true, // 是否显示取消按钮
                                cancelText: "否", // 默认是“取消”
                                cancelColor: 'skyblue', // 取消文字的颜色
                                confirmText: "是", // 默认是“确定”
                                confirmColor: 'skyblue', // 确定文字的颜色
                                success: function (res) {
                                    if (res.cancel) { // 点击取消,默认隐藏弹框
                                    } else { // 点击确定
                                        new TbCommunityUserService().visitTbCommunity(scanResult.tbCommunityUser).then(result => {
                                            if (result.status === "success") {
                                                _self.globalVariable.userInfo = result.userInfo;
                                                LocalStorageUtil.setItem("userInfo", _self.globalVariable.userInfo);

                                                // 保存扫码关联的餐饮号
                                                _self.globalVariable.orderSequenceNumber = scanResult.tbCommunityUser.orderSequenceNumber;
                                                _self.$forceUpdate();
                                                CommonUtil.alert("访问成功，开始您的购物之旅吧！");
                                            } else {
                                                CommonUtil.alert(result.message);
                                            }
                                        });
                                    }
                                },
                                fail: function (res) {
                                }, // 接口调用失败的回调函数
                                complete: function (res) {
                                } // 接口调用结束的回调函数（调用成功、失败都会执行）
                            })
                        } else {
                            CommonUtil.toast("二维码无效");
                        }
                    });
                }
            },
            /**
             * 切换登录的商城
             * @param tbCommunityUser
             */
            switchCommunity(tbCommunityUser) {
                this.actionSheetActions.forEach(item => {
                    item.disabled = false;
                });
                this.isShowSwitchCustomer = false;

                // 已经是选中的商城，则禁止切换商城选项
                if (this.globalVariable.userInfo.tbCommunityUser.id === tbCommunityUser.id) {
                    this.actionSheetActions[0].disabled = true;
                }
                // 如果是禁止登录的商城，则禁止切换商城选项
                if (!tbCommunityUser.enabledLogin) {
                    this.actionSheetActions[0].disabled = true;
                    this.actionSheetActions[1].disabled = true;
                }

                // 如果是默认商城，则禁止设为默认选项
                if (tbCommunityUser.isDefault) {
                    this.actionSheetActions[1].disabled = true;
                }

                // 如果是业务员，则显示切换客户选项
                if (tbCommunityUser.tbCommunity.id === this.globalVariable.userInfo.tbCommunityUser.tbCommunity.id &&
                    this.globalVariable.userInfo.tbCommunityUser.type === "0") {  // type=0业务员，1-客户
                    this.isShowSwitchCustomer = true;
                }

                this.tbCommunityUser = tbCommunityUser;
                this.isShowActionSheet = true;
            },
            onCancel() {
                this.isShowActionSheet = false;
                this.isShowPasteQRCodeActionSheet = false;
                this.isShowQrCode = false;
            },
            onSelect(item, index) {
                const _self = this;
                this.isShowActionSheet = false;
                // 切换到该商城
                if (item.code === 1) {
                    // 如果当前就是了，无需在操作。
                    if (_self.tbCommunityUser.tbCommunity.id === _self.globalVariable.userInfo.tbCommunity.id) {
                        if (!_self.globalVariable.orderSequenceNumber) {//  不是餐饮店
                            CommonUtil.alert("你正在访问该商城");
                        } else {
                            CommonUtil.alert("开始您的购物之旅吧！");  // 餐饮店，扫码已获取餐饮号
                        }
                        return;
                    }
                    // 更新后台session数据
                    new SysUserService().updateSessionData({
                        tbCommunity: _self.tbCommunityUser.tbCommunity,
                        tbCommunityAdmin: _self.tbCommunityUser.tbCommunityAdmin,
                        tbCommunityUserList: [_self.tbCommunityUser]
                    }).then(result => {
                        _self.globalVariable.userInfo = result.userInfo;
                        LocalStorageUtil.setItem("userInfo", _self.globalVariable.userInfo);

                        if (_self.tbCommunityUser.type === "0") {  // type=0业务员，1-客户
                            uni.reLaunch({
                                url: '/pages/common/login-community-user-select/index?returnPageUrl=pages/sub/sub1-tabs/tabs/index'
                            });
                        } else {
                            CommonUtil.alert("商城切换成功").then(() => {
                                uni.reLaunch({url: '/pages/sub/sub1-tabs/tabs/index'})
                            });
                        }
                    });
                } else if (item.code === 2) { // 设为默认
                    if (_self.tbCommunityUser.isDefault) {
                        CommonUtil.alert("已是默认状态");
                    } else {
                        new TbCommunityUserService().setDefaultTbCommunityUser({
                            id: _self.tbCommunityUser.id,
                            userId: _self.tbCommunityUser.userId
                        }).then(result => {
                            CommonUtil.alert("设置成功");
                            if (_self.globalVariable.userInfo.tbCommunityUser.id === _self.tbCommunityUser.id) {
                                _self.globalVariable.userInfo.tbCommunityUser.isDefault = true;
                            }
                            _self.globalVariable.userInfo.tbCommunityUserList.forEach(item => {
                                if (item.id === _self.tbCommunityUser.id) {
                                    item.isDefault = true;
                                } else {
                                    item.isDefault = false;
                                }
                            });
                        })
                    }
                }
            },
            /**
             * 如果是业务员，则可以快速切换客户
             */
            switchCustomer() {
                const _self = this;
                this.isShowActionSheet = false;
                uni.navigateTo({
                    url: '/pages/common/login-community-user-select/index?returnPageUrl=pages/sub/sub1-tabs/tabs/index'
                });
            },
            /**
             * 显示商城二维码
             */
            showQRCode() {
                const _self = this;
                this.isShowActionSheet = false;
                this.isShowQrCode = true;
                uQRCode.make({
                    canvasId: 'qrcode',
                    componentInstance: this,
                    text: this.tbCommunityUser.tbCommunity.qrCode,  // 二维码内容
                    size: 150,
                    margin: 10,
                    backgroundColor: '#ffffff',
                    foregroundColor: '#000000',
                    fileType: 'jpg',
                    correctLevel: uQRCode.errorCorrectLevel.H,
                    success: res => {
                        console.log(res)
                    }
                })
            },
            /**
             * 全屏显示二维码，长按可以保存二维码图片
             */
            previewImage() {
                // 在自定义组件下，当前组件实例的 this，以操作组件内 <canvas> 组件
                uni.canvasToTempFilePath({
                    canvasId: 'qrcode',
                    success: function (res) {
                        // 在H5平台下，tempFilePath 为 base64
                        console.log(res.tempFilePath)

                        // 预览图片
                        uni.previewImage({
                            urls: [res.tempFilePath],
                        });
                    }
                })
            },
            /**
             * 显示粘贴二维码内容弹框
             */
            showPasteQRCodeActionSheet() {
                this.pasteQRCode = "";
                this.isShowPasteQRCodeActionSheet = true;
            },
            /**
             * 识别二维码内容
             */
            recognizeQRCode() {
                this.isShowPasteQRCodeActionSheet = false;
                setTimeout(() => {
                    this.handleQrCode(this.pasteQRCode);
                }, 100)
            },
        }
    }
</script>

<style lang="scss" scoped>
</style>
